<?php
require_once(dirname(__FILE__) . "/../system/common.inc.php");
$dopost = isset($dopost) ? $dopost : '';
$buyid  = isset($out_trade_no) ? HtmlReplace($out_trade_no, 1) : '';
if ($dopost === 'alipay')
{
    if (substr($buyid, 0, 3) == 'KE-')
    {
        //检查支付金额是否相符
        $row = $dsql->GetOne("SELECT * FROM #@__shops_orders WHERE oid = '{$buyid}'");
        if (empty($row))
        {
            ShowMsg("订单查询错误，请确保是您自己发起的订单", "javascript:;");
            exit;
        }
        if ($row['priceCount'] != $_GET['total_amount'])
        {
            ShowMsg("支付失败，支付金额与商品总价不相符!", "javascript:;");
            exit;
        }
        $ordertype = "goods";
        $mid       = $row['userid'];
    }
    else if (preg_match("/M[0-9]+T[0-9]+RN[0-9]/", $buyid))
    {
        $row = $dsql->GetOne("SELECT * FROM #@__member_operation WHERE buyid = '{$buyid}'");
        if (empty($row))
        {
            ShowMsg("订单查询错误，请确保是您自己发起的订单", "javascript:;");
            exit;
        }
        if ($row['sta'] == 2)
        {
            header('Location:/user/weixinpay/ok.php?ddh=' . $buyid);
            exit();
        }
        elseif ($row['money'] != $_GET['total_amount'])
        {
            ShowMsg("支付失败，支付金额与商品总价不相符!", "javascript:;");
            exit;
        }
        $ordertype = "member";
        $product   = $row['product'];
        $pname     = $row['pname'];
        $pid       = $row['pid'];
        $mid       = $row['mid'];
    }
    else
    {
        ShowMsg("订单查询错误，请确保是您自己发起的订单", "javascript:;");
        exit;
    }
    if (!file_exists(DEDEDATA . '/payment/alipay.php'))
    {
        ShowMsg("未发现支付接口文件，请到后台配置！", 'javascript:;');
        exit();
    }
    require_once DEDEDATA . '/payment/alipay.php';
    $config = array(
        "sign_type"   => "RSA2",
        "appid"       => $payment['app_id'],
        "private_key" => $payment['merchant_private_key'],
        "public_key"  => $payment['alipay_public_key'],
    );
    //支付宝
    try
    {
        //实例支付对象
        $pay = \AliPay\Web::instance($config);
        unset($_REQUEST['dopost']);
        unset($_REQUEST['sign_type']);
        $data = $pay->notify(false, $_REQUEST);
        if (isset($data['trade_no']) && !empty($data['trade_no']))
        {
            $result = $pay->query($data['out_trade_no']);
            if ($result['trade_status'] === "TRADE_SUCCESS")
            {
                if ($ordertype == "goods")
                {
                    //获取订单信息，检查订单的有效性
                    $arr = $dsql->GetOne("SELECT * FROM #@__shops_orders WHERE oid='$buyid' ");
                    if ($arr['state'] > 0)
                    {
                        header('Location:/user/weixinpay/ok.php?ddh=' . $buyid);
                        exit();
                    }
                    /* 改变订单状态_支付成功 */
                    $sql = "UPDATE `#@__shops_orders` SET `state`='1', paytype='11' WHERE `oid`='$buyid' AND `userid`='" . $mid . "'";
                    if ($dsql->ExecuteNoneQuery($sql))
                    {
                        //作者：覃小华 2019年10月18日14:08:11 推广购课部分
                        //1、推荐人加佣金 2、付款人改成已购买用户  3、写收益记录
                        $typearr      = $dsql->GetOne("SELECT typename FROM  #@__arctype WHERE id = '" . $arr['pid'] . "' ");
                        $arr['mid']   = $arr['userid'];
                        $arr['money'] = $arr['priceCount'];
                        $tjrarr       = $dsql->GetOne("SELECT tjrmid FROM #@__member WHERE mid = '" . $arr['mid'] . "'");
                        if (!empty($tjrarr['tjrmid']))
                        {
                            global $cfg_keyjbl;
                            $time    = time();
                            $yongjin = $arr['money'] * $cfg_keyjbl / 100;
                            $yongjin = number_format($yongjin, 2);
                            $tjrmid  = $tjrarr['tjrmid'];
                            $sql     = "UPDATE #@__member set shouyi = (shouyi + $yongjin) WHERE mid = '$tjrmid'";
                            $dsql->ExecuteNoneQuery($sql);
                            $sql = "UPDATE #@__member SET yigoumai = '1' WHERE mid = '" . $arr['mid'] . "'";
                            $dsql->ExecuteNoneQuery($sql);
                            $sql = "INSERT INTO #@__jj_shouyi (`tjrmid`,`mid`,`jine`,`chanpin`,`yongjin`,`time`,`tid`  ) VALUES ('$tjrmid','" . $arr['mid'] . "','" . $arr['money'] . "','" . $typearr['typename'] . "','$yongjin','$time','" . $arr['pid'] . "')";
                            $dsql->ExecuteNoneQuery($sql);
                        }
                        //推荐end
                        header('Location:/user/weixinpay/ok.php?ddh=' . $buyid);
                        exit();
                    }
                    else
                    {
                        ShowMsg("支付失败", "javascript:;");
                        exit;
                    }
                }
                else if ($ordertype == "member")
                {
                    //更新交易状态为已付款
                    $sql = "UPDATE `#@__member_operation` SET `sta`='1' WHERE `buyid`='$buyid' AND `mid`='" . $mid . "'";
                    $dsql->ExecuteNoneQuery($sql);
                    /* 改变点卡订单状态_支付成功 */
                    if ($product == "card")
                    {
                        $row = $dsql->GetOne("SELECT cardid FROM #@__moneycard_record WHERE ctid='$pid' AND isexp='0' ");;
                        //如果找不到某种类型的卡，直接为用户增加金币
                        if (!is_array($row))
                        {
                            $nrow   = $dsql->GetOne("SELECT num FROM #@__moneycard_type WHERE pname = '{$pname}'");
                            $dnum   = $nrow['num'];
                            $sql1   = "UPDATE `#@__member` SET `money`=money+'{$nrow['num']}' WHERE `mid`='" . $mid . "'";
                            $oldinf = "已经充值了" . $nrow['num'] . "金币到您的帐号！";
                        }
                        else
                        {
                            $cardid = $row['cardid'];
                            $sql1   = " UPDATE #@__moneycard_record SET uid='" . $mid . "',isexp='1',utime='" . time() . "' WHERE cardid='$cardid' ";
                            $oldinf = '您的充值密码是：<font color="green">' . $cardid . '</font>';
                        }
                        //更新交易状态为已关闭
                        $sql2 = " UPDATE #@__member_operation SET sta=2,oldinfo='$oldinf' WHERE buyid='$buyid'";
                        if ($dsql->ExecuteNoneQuery($sql1) && $dsql->ExecuteNoneQuery($sql2))
                        {
                            header('Location:/user/weixinpay/ok.php?ddh=' . $buyid);
                            exit();
                        }
                        else
                        {
                            ShowMsg("充值失败", "javascript:;");
                            exit;
                        }
                        /* 改变会员订单状态_支付成功 */
                    }
                    else if ($product == "member")
                    {
                        $row     = $dsql->GetOne("SELECT rank,exptime FROM #@__member_type WHERE aid='$pid' ");
                        $rank    = $row['rank'];
                        $exptime = $row['exptime'];
                        /*计算原来升级剩余的天数*/
                        $rs = $dsql->GetOne("SELECT uptime,exptime FROM #@__member WHERE mid='" . $mid . "'");
                        if ($rs['uptime'] != 0 && $rs['exptime'] != 0)
                        {
                            $nowtime = time();
                            $mhasDay = $rs['exptime'] - ceil(($nowtime - $rs['uptime']) / 3600 / 24) + 1;
                            $mhasDay = ($mhasDay > 0) ? $mhasDay : 0;
                        }
                        //获取会员默认级别的金币和积分数
                        $memrank = $dsql->GetOne("SELECT money,scores FROM #@__arcrank WHERE rank='$rank'");
                        //更新会员信息
                        $sql1 = " UPDATE #@__member SET rank='$rank',money=money+'{$memrank['money']}', scores=scores+'{$memrank['scores']}',exptime='$exptime'+'$mhasDay',uptime='" . time() . "' WHERE mid='" . $mid . "'";
                        //更新交易状态为已关闭
                        $sql2 = " UPDATE #@__member_operation SET sta='2',oldinfo='会员升级成功!' WHERE buyid='$buyid' ";
                        if ($dsql->ExecuteNoneQuery($sql1) && $dsql->ExecuteNoneQuery($sql2))
                        {
                            //作者：覃小华 2019年1月22日09:30:45 推广注册部分
                            //1、推荐人加佣金 2、付款人改成已购买用户  3、写收益记录（SVIP购买返现）
                            $tjrarr = $dsql->GetOne("SELECT tjrmid FROM #@__member WHERE mid = '" . $mid . "'");
                            file_put_contents("aarr_tjrarr.txt",print_r($tjrarr,true).PHP_EOL,FILE_APPEND);
                            if (!empty($tjrarr['tjrmid']))
                            {
                                global $cfg_tgyjbl;
                                $time    = time();
                                $yongjin = $data['total_amount'] * $cfg_tgyjbl / 100;
                                $yongjin = number_format($yongjin, 2);
                                $tjrmid  = $tjrarr['tjrmid'];
                                $sql     = "UPDATE #@__member set shouyi = (shouyi + $yongjin) WHERE mid = '$tjrmid'";
                                file_put_contents("aarr_sql1.txt",print_r($sql,true).PHP_EOL,FILE_APPEND);
                                $dsql->ExecuteNoneQuery($sql);
                                $sql = "UPDATE #@__member SET yigoumai = '1' WHERE mid = '" . $arr['mid'] . "'";
                                file_put_contents("aarr_sql2.txt",print_r($sql,true).PHP_EOL,FILE_APPEND);
                                $dsql->ExecuteNoneQuery($sql);
                                $sql = "INSERT INTO #@__jj_shouyi (`tjrmid`,`mid`,`jine`,`chanpin`,`yongjin`,`time` ) VALUES ('$tjrmid','" . $arr['mid'] . "','" . $arr['money'] . "','" . $arr['pname'] . "','$yongjin','$time')";
                                file_put_contents("aarr_sql3.txt",print_r($sql,true).PHP_EOL,FILE_APPEND);
                                $dsql->ExecuteNoneQuery($sql);
                            }
                            //推荐end
                            header('Location:/user/weixinpay/ok.php?ddh=' . $buyid);
                            exit();
                        }
                        else
                        {
                            ShowMsg("会员升级失败！", "javascript:;");
                            exit;
                        }
                    }
                }
            }
        }
        else
        {
            ShowMsg("尚未完成付款操作", $cfg_memberurl . "/index.php");
            exit;
        }
    } catch (Exception $e)
    {
        ShowMsg("付款失败，请检查支付接口设置", "javascript:;");
        exit;
    }
}
else
{
    ShowMsg("未知付款，请检查支付接口设置", "javascript:;");
    exit;
}
